package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.acticle.domain.Answer;
import cn.wolfcode.luowowo.acticle.domain.AnswerContent;
import cn.wolfcode.luowowo.acticle.domain.Query;
import cn.wolfcode.luowowo.acticle.query.AnswerQuery;
import cn.wolfcode.luowowo.acticle.service.IAnswerService;
import cn.wolfcode.luowowo.acticle.service.IQueryService;
import cn.wolfcode.luowowo.cache.key.RedisKeys;
import cn.wolfcode.luowowo.cache.service.IAnswerRedisService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/answer")
@Controller
public class AnswerController {

    @Reference
    private IAnswerService answerService;

    @Reference
    private IAnswerRedisService answerRedisService;

    @Reference
    private IQueryService queryService;

    @RequireLogin
    @RequestMapping("saveAnswer")
    @ResponseBody
    public AjaxResult saveAnswer(@ModelAttribute("qo")AnswerQuery qo, Answer answer, @UserParam UserInfo userInfo){
        //添加回答
        answer.setAuthor(userInfo);
        //当前问题
        Query query = new Query();
        query.setId(qo.getId());
        answer.setQuery(query);
        answerService.saveAnswer(answer);

        //用户回复+1
        answerRedisService.commentUp(userInfo.getId());
        answerRedisService.addScore(RedisKeys.USER_STATIS_VO_COMMENT_USER.getPrefix(),
                RedisKeys.USER_STATIS_VO_COMMENT.join(userInfo.getId().toString()),1);

        //问题回复数+1
        int replay = queryService.getReplay(qo.getId());
        queryService.setReply(qo.getId(),replay+1);

        return AjaxResult.SUCCESS().addData(qo.getId());
    }

    @RequestMapping("answerThumbup")
    @ResponseBody
    public Object answerThumbup(Long aid,@UserParam UserInfo userInfo) {
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false,"请先进行登录");
            result.setCode(102);
            return result;
        }

        boolean ret = answerRedisService.thumbup(aid, userInfo.getId());
        answerRedisService.addScore(RedisKeys.ANSWER_STATIS_THUMB_USER.getPrefix(),
                                    RedisKeys.ANSWER_STATIS_THUMB.join(aid.toString()),1);
        return new AjaxResult(ret, "").addData(answerRedisService.getStatisvo(aid));
    }

}
